<!--  -->
<template>
  <div>
    <van-pull-refresh
      :success-duration="1500"
      v-model="refreshing"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
    >
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadArticles">
        <article-item v-for="(article, index) in list" :key="index" :article="article"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/user'
import ArticleItem from '@/components/article-item'
export default {
  props: {
    channelist: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      paramObj: {},
      refreshSuccessText: '刷新成功', // 下拉刷新成功提示文本
      timestamp: null // 请求下一页数据的时间戳
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.loadArticles()
  },
  components: {
    ArticleItem
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    onRefresh() {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    loadArticles() {
      // console.log(this.channelist.id)
      this.paramObj = {
        channel_id: this.channelist.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      }
      try {
        getArticles.loadArticles(this.paramObj).then(data => {
          const { results } = data.data
          console.log(results)
          this.list.push(...results)

          this.loading = false
          if (results.length) {
            // 更新获取下一页数据的时间戳
            this.timestamp = data.data.pre_timestamp
          } else {
            // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
            this.finished = true
          }
        })
      } catch (err) {
        this.loading = false
        this.error = true
      }
    },
    onRefresh() {
      try {
        getArticles.loadArticles(this.paramObj).then(data => {
          const { results } = data.data
          this.list.unshift(...results)
          this.refreshing = false
          // console.log(`刷新成功，更新了${results.length}条数据`)
          this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
        })
      } catch (error) {
        this.refreshing = false
        this.$toast('刷新失败')
      }
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.article-list {
  position: fixed;
  top: 180px;
  bottom: 100px;
  right: 0;
  left: 0;
  overflow-y: auto;
}
</style>